package com.ay.selfservicemachine.webview;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.lang.UCharacter;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.ay.selfservicemachine.R;
import com.ay.selfservicemachine.base.BaseActivity;
import com.ay.selfservicemachine.base.HQWAppCompatActivity;
import com.ay.selfservicemachine.base.Presenter;
import com.ay.selfservicemachine.bean.UpdateBean;
import com.ay.selfservicemachine.dialog.UpdateDialog;
import com.ay.selfservicemachine.http.ApiExceptionClassifierReport;
import com.ay.selfservicemachine.http.dialog.LoadingDialogUtils;
import com.ay.selfservicemachine.utils.Logger;
import com.ay.selfservicemachine.utils.ToastUtil;
import com.honghea.rxhttp.exception.ApiException;
import com.sdses.bean.ID2Data;
import com.sdt.Sdtapi;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;


public class WebPresenter extends Presenter<IWebView> implements IWebViewModuleCallback {


    public void setSetting(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//https http混淆
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setGeolocationEnabled(true);
        webView.addJavascriptInterface(new JsCallback(), "CallAndroidInterface");
    }


    private class JsCallback extends Object {//JS和app交互

        @JavascriptInterface
        public void checkAppVersion() {//检查更新
            getView().checkAppVersion();
        }

        @JavascriptInterface
        public void jsSaveUrl() {//设置链接地址

        }

        @JavascriptInterface
        public String jsGetCardInfo() {//读身份证卡信息
            return readIdCardInfo();
        }

        @JavascriptInterface
        public void jsCloseDevices() {//主动关闭身份证读取
//            sdtapi = null;
//            m_bSAMUSBState = false;
        }
    }

//******************************************** 读取身份证卡信息 *********************************

    boolean is_close = false;
    boolean m_bSAMUSBState = false;//读卡设备usb连接状态
    Sdtapi sdtapi; //读卡必需

    public void initIdCardSdt(){
        try {
            sdtapi = new Sdtapi((BaseActivity)getView());    //读卡会用到
            if(sdtapi != null){
                m_bSAMUSBState = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
//            ToastUtil.toastLongMessage("初始话失败");
        }
    }

    public String readIdCardInfo(){
        JSONObject json = new JSONObject();
        try {
            initIdCardSdt();
            if(!m_bSAMUSBState ){
                json.put("code", 1);
                json.put("date", null);
                json.put("msg", "USB设备异常或无连接");
                return json.toString();
            }


            byte[] data = new byte[1280];
            int[] txtDataLen = new int[1];
            int[] photoDataLen = new int[1];
            byte[] txtData = new byte[256];
            byte[] photoData = new byte[1024];
            sdtapi.SDT_StartFindIDCard();//寻卡
            sdtapi.SDT_SelectIDCard();//选卡
            int nRet = sdtapi.SDT_ReadBaseMsg(txtData, txtDataLen, photoData, photoDataLen);
            if(nRet == 0x90){
                System.arraycopy(txtData,   0, data, 0, 256);
                System.arraycopy(photoData, 0, data, 256, 1024);

                //获取身份证name,num
                ID2Data _id2data = new ID2Data();
                _id2data.clearID2DataRAW();
                _id2data.decode_debug(data);
                _id2data.rePackage();
                String name = _id2data.getmID2Txt().getmName();
                String idNum = _id2data.getmID2Txt().getmID2Num();

                JSONObject dateObj = new JSONObject();
                dateObj.put("peopleName", name);
                dateObj.put("iDCard", idNum);

                json.put("code", 0);
                json.put("date", dateObj);
                json.put("msg", "");
            } else{
                json.put("code", 1);
                json.put("date", null);
                json.put("msg", "未放卡或读卡失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return json.toString();
    }


    //*****************************************************选择照片**********************************
    public void selectPhoto() {//选择照片
//        ((BaseActivity) getView()).runOnUiThread(() -> {
//            PhotoCommander.startCamera((BaseActivity) getView(), new PhotoCommander.SelectAlbumCallback() {
//                @Override
//                public void photo(String photoPath) {
//                    String base64Image = "data:image/png;base64," + HQWImageUtil.BitmapToBase64(ImageUtil.getBitmapFormPath(photoPath));
//                    getView().getWebView().evaluateJavascript("observerPhotoMessage(\"" + Base64Utils.encodeString(base64Image) + "\")", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String value) {
//                        }
//                    });
//                }
//            });
//        });
    }


    //*****************************************************监听webview事件**********************************

    public void clientListener(WebView webView) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
                    view.loadUrl(url);
                    return super.shouldOverrideUrlLoading(view, request);
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    if (intent.resolveActivity(((Context) getView()).getPackageManager()) != null) {
                        view.getContext().startActivity(intent);
                    } else {
                        ToastUtil.toastShortMessage("没有任何应用程序可以处理它");
                    }
                    return true;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                getView().showHttpError(false);
            }


            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                switch (error.getErrorCode()) {
                    case 404:
                        break;
                    case -2:
                        getView().showHttpError(true);
                        break;
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                getView().setLoadingProgress(newProgress);
            }
        });
    }

    /********************************** 检查更新 **************************************/

    public void startCheckAppVersion(){//开始检查更新
        webModule.checkAppVersion();
    }


    @Override
    public void onCheckUpdateSuccess(UpdateBean updateBean) {
        Logger.e("Met","3333333333");
        Logger.e("Met",updateBean.toString());
        if (updateBean.getUpdateVersion() != null) {
            UpdateDialog updateDialog = new UpdateDialog((Context) getView(), (HQWAppCompatActivity) getView());
            updateDialog.show();
            updateDialog.setUpdateBean(updateBean);
            updateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {

                }
            });
        }
    }

    @Override
    public void onCheckUpdateFailed(ApiException e) {
        ToastUtil.toastLongMessage(e.msg);
        ApiExceptionClassifierReport.afterApiExceptionThrow(e);
    }

    @Override
    public void showCheckUpdateDialog() {
        LoadingDialogUtils.getInstance().buildDialog((WebActivity) getView(), R.string.dialog_loading, "CheckUpdate", false).show();
    }

    @Override
    public void dismissCheckUpdateDialog() {
        LoadingDialogUtils.getInstance().loadDialogDismiss("CheckUpdate");
    }

    /**********************************Module**************************************/
    WebModule webModule;

    public String title = "";
    public String url = "https://ticket.an-yin.com/ticketSelfH5/#/index";//自助机地址

    @Override
    public void initData() {
        super.initData();
//        if (url.endsWith(".pdf")) {
//            url="https://docs.google.com/gview?embedded=true&url="+url;
//        }

        getView().setTitle(title);
        getView().setUrl(url);
//        getView().setUrl("file:///android_asset/index.html");
    }

    @Override
    protected void resetView() {

    }

    @Override
    public void initModule() {
        if (perPageData.containsKey("title")) {
            title = (String) perPageData.get("title");
        }
        if (perPageData.containsKey("url")) {
            url = (String) perPageData.get("url");
        }

        webModule = new WebModule();
        webModule.attachPresenter(this);
    }

    @Override
    public void releaseModule() {
        webModule.detachPresenter();
    }

}
